package formal.tree.bst;

/**
 * @author DengYuan2
 * @create 2021-01-21 22:19
 */
public class E_669 {
    public static void main(String[] args) {
        Integer[] a = {3, 0, 4, null, 2, null, null, 1, null};
        TreeNode treeNode = TreeNode.generateTree(a);
        TreeNode res = trimBST(treeNode, 2, 3);
        System.out.println(res);

    }

    /**
     * 我的写法-与大神的一致
     *
     * @param root
     * @param low
     * @param high
     * @return
     */
    public static TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) {
            return null;
        }
        if (root.val < low) {
            return trimBST(root.right, low, high);
        }
        if (root.val > high) {
            return trimBST(root.left, low, high);
        }
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        return root;
    }


    /**
     * 官方-迭代法
     *
     * @param root
     * @param low
     * @param high
     * @return
     */
    public static TreeNode trimBST2(TreeNode root, int low, int high) {
        if (root == null) {
            return null;
        }
        //将root放到[low,high]内
        while (root.val < low || root.val > high) {
            root=(root.val<low)?root.right:root.left;
        }
        TreeNode cur =root;
        //剪掉左边<low的
        while (cur!=null){
            while (cur.left!=null && cur.left.val<low){
                cur.left=cur.left.right;
            }
            cur=cur.left;
        }
        cur=root;
        //剪掉右边>high的
        while (cur!=null){
            while (cur.right!=null&&cur.right.val>high){
                cur.right=cur.right.left;
            }
            cur=cur.right;
        }
        return root;
    }
}
